package top.jiaman.javaweb.servlet.user;

import top.jiaman.javaweb.dao.UserDAOImpl;
import top.jiaman.javaweb.entity.BaseResponse;
import top.jiaman.javaweb.entity.User;
import top.jiaman.javaweb.util.RequestUtil;
import com.google.gson.Gson;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author Jiaman
 * @Date 2020/12/4 9:24
 * @Desc
 */

@WebServlet(urlPatterns = "/user/add")
public class UserAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        Gson gson = new Gson();
        String userJson = RequestUtil.getRequestBody(req);
        User userBody = gson.fromJson(userJson, User.class);

        UserDAOImpl uas = UserDAOImpl.getInstance();
        int rows = uas.insert(userBody);

        BaseResponse<Integer> baseResponse = new BaseResponse<>();
        if (rows > 0) {
            baseResponse.setCode(200);
            baseResponse.setMsg("操作成功");
        }else {
            baseResponse.setCode(500);
            baseResponse.setMsg("操作失败");
        }

        baseResponse.setData(rows);
        String json = gson.toJson(baseResponse);
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.print(json);
        out.flush();
    }
}
